<template>
  <div class="form-wapper">
    <van-nav-bar
      :title="$route.meta.title"
      left-arrow
      :border="false"
      @click-left="clickLeft"
      @click-right="clickRight"
    >
      <template #right>
        <van-icon name="success" size="24" />
        <span
          style="
            margin-left: 2px;
            color: #fff;
            margin-top: 3px;
            font-size: 20px;
          "
          >保存</span
        >
      </template>
    </van-nav-bar>
    <div class="sampleItem">
      <van-form @submit="onSubmit" ref="subForm" scroll-to-error>
        <van-row type="flex">
          <van-col span="12" class="readonly">
            <van-field
              v-model="materName"
              name="materName"
              label="检品名称"
              input-align="center"
              readonly
            >
            </van-field>
          </van-col>
          <van-col span="12" class="readonly">
            <van-field
              v-model="batchID"
              name="batchID"
              label="批号"
              input-align="center"
              readonly
            >
            </van-field>
          </van-col>
          <van-col span="12" class="readonly">
            <van-field
              v-model="sampleDate"
              name="sampleDate"
              label="实际取样日期"
              input-align="center"
              readonly
            >
            </van-field>
          </van-col>
          <van-col span="12" class="readonly">
            <van-field
              v-model="point"
              name="point"
              label="来源"
              input-align="center"
              readonly
            >
            </van-field>
          </van-col>
          <van-col span="12" class="readonly">
            <van-field
              v-model="sampleCount"
              name="sampleCount"
              label="拟取样数量"
              input-align="center"
              readonly
            >
            </van-field>
          </van-col>
          <van-col span="12" class="readonly">
            <van-field
              v-model="currentResidueCount"
              name="currentResidueCount"
              label="当前剩余量"
              input-align="center"
              readonly
            >
            </van-field>
          </van-col>
          <van-col span="24" class="readonly">
            <van-field
              v-model="attributeStr"
              name="attributeStr"
              label="检验项目"
              input-align="center"
              readonly
            >
            </van-field>
          </van-col>
        </van-row>
      </van-form>
      <div
        style="display: flex; justify-content: space-between; margin-top: 20px"
      >
        <van-tag plain type="primary" style="margin: 20px 10px 10px 10px"
          >检验</van-tag
        >
        <div>
          <van-button
            size="mini"
            type="info"
            style="
              float: right;
              margin-right: 25px;
              margin-top: 10px;
              padding: 0px 20px;
            "
            @click="addCheckData()"
            >添加</van-button
          >
        </div>
      </div>
      <van-row>
        <van-col span="12">
          <van-field
            v-model="ClassID"
            name="ClassID"
            label="班组"
            input-align="center"
          >
            <template #input>
              <select-two
                v-model="ClassID"
                :dataList="classArr"
                @change="getClassName"
              />
            </template>
          </van-field>
        </van-col>
        <van-col span="12">
          <van-field
            v-model="Specification"
            name="Specification"
            label="规格"
            input-align="center"
          >
            <!-- <template #input>
              <select-two
                v-model="Specification"
                :dataList="SpecificationArr"
                @change="getSpecificationName"
              />
            </template> -->
          </van-field>
        </van-col>
        <van-col span="8" style="width: 31%">
          <van-field
            v-model="Count"
            name="Count"
            label="数量"
            input-align="center"
          >
          </van-field>
        </van-col>
        <van-col span="4" style="width: 19%">
          <van-field v-model="Unit" name="Unit" placeholder="请选择">
            <template #input>
              <picker-unit v-model="Unit" @change="getUnitName" />
            </template>
          </van-field>
        </van-col>
        <van-col span="12">
          <van-field
            v-model="ResidueCount"
            name="ResidueCount"
            label="剩余数量"
            input-align="center"
          >
          </van-field>
        </van-col>
      </van-row>
      <div style="padding: 0 20px; margin: 20px 0">
        <table class="tb">
          <tr>
            <th>班组</th>
            <th>规格</th>
            <th>数量</th>
            <th>单位</th>
            <th>剩余数量</th>
            <th>操作</th>
          </tr>
          <tr v-for="(item, index) in checkList" :key="index">
            <td>{{ item.ClassName }}</td>
            <!-- <td>{{ item.SpecificationName }}</td> -->
            <td>{{ item.Specification }}</td>
            <td>{{ item.Count }}</td>
            <td>{{ item.UnitName }}</td>
            <td>{{ item.ResidueCount }}</td>
            <td>
              <button @click="delData(index)">删除</button>
            </td>
          </tr>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import {
  Form,
  Field,
  NavBar,
  Button,
  Popup,
  Toast,
  Col,
  Row,
  Checkbox,
  CheckboxGroup,
  TreeSelect,
  Notify,
  Icon,
  Tag,
} from "vant";
import PickerUnit from "./components/PickerUnit";
import PickerDate from "@/components/PickerDate";
import PickerDateOne from "@/components/PickerDateOne";
import FixedSelect from "@/components/FixedSelect";
import SelectOne from "@/components/SelectOne";
import FixedSelectOne from "@/components/FixedSelectOne";
import MultSelect from "@/components/MultSelect";
import SelectTwo from "@/components/SelectTwo";

import {
  SaveStabilitySampleData,
  GetSampleRecordHeadById,
  GetSampleSpecificationSelect,
} from "@/api/check";
import { getInfoTree, GetUserList } from "@/api/base";

export default {
  components: {
    [Form.name]: Form,
    [Field.name]: Field,
    [NavBar.name]: NavBar,
    [Button.name]: Button,
    [Popup.name]: Popup,
    [Toast.name]: Toast,
    [Col.name]: Col,
    [Row.name]: Row,
    [Checkbox.name]: Checkbox,
    [CheckboxGroup.name]: CheckboxGroup,
    [TreeSelect.name]: TreeSelect,
    [Notify.name]: Notify,
    [Icon.name]: Icon,
    [Tag.name]: Tag,
    PickerUnit,
    PickerDate,
    FixedSelect,
    SelectOne,
    MultSelect,
    PickerDateOne,
    FixedSelectOne,
    SelectTwo,
  },
  props: {},
  data() {
    return {
      addData: {},
      rowData: {},
      token: "",
      testId: "",
      materName: "",
      materialCode: "",
      batchID: "",
      sampleDate: "", //实际取样日期
      currentDate: new Date(),
      point: "", //来源
      sampleCount: "", //拟取样数量
      currentResidueCount: "", //当前剩余量
      attributeList: [], //检验项目
      attributeStr: "",
      materialTypeName: "",
      materialType: "",
      classArr: [], //班组
      ClassName: "",
      ClassID: "",
      Specification: "", //规格
      // SpecificationName: "",
      SpecificationArr: [],
      Count: "", //数量
      Unit: "", //单位
      UnitName: "",
      checkList: [], //检验list
      ResidueCount: "",
    };
  },
  watch: {},
  methods: {
    clickLeft() {
      this.$router.replace({ name: "mySampling" });
    },
    clickRight() {
      this.$refs.subForm.submit();
    },
    async onSubmit(values) {
      var that = this;
      var q = values;
      var attributes = [];
      this.attributeList.map((item) => {
        attributes.push({
          id: "",
          value: item.AttributeCode,
          text: item.AttributeName,
        });
      });
      q["Token"] = this.token;
      q["iautoid"] = this.rowData.iautoid;
      q["type"] = this.rowData.cycleCode;
      q["SampleDetail"] = this.checkList;
      q["attributeList"] = this.attributeStr;
      q["attributes"] = attributes;
      SaveStabilitySampleData(q)
        .then((response) => {
          Notify({ type: "success", message: response.ErrorMsg });
          if (response.ErrorCode == 0) {
            this.$router.replace({ name: "mySampling" });
          }
        })
        .catch(() => {});
    },
    getInfoByTestId() {
      var params = {
        Token: this.token,
        TestID: this.testId,
      };
      GetSampleRecordHeadById(params)
        .then((response) => {
          if (response.ErrorCode == 0) {
            this.addData = response.Result;
            this.materName = this.addData.MaterialName;
            this.materialCode = this.addData.MaterialCode;
            this.MaterialTypeName = this.addData.MaterialTypeName;
            this.MaterialType = this.addData.MaterialType;
            this.batchID = this.addData.BatchID;
            this.point = this.rowData.areaName;
            this.sampleCount = this.rowData.sampleCount;
            this.currentResidueCount = this.rowData.currentResidueCount;
          }
        })
        .catch(() => {});
    },
    getSampleUserId() {
      var params = {
        Token: this.token,
        searchdepartment: ["QA"],
        Rows: 1000,
        Page: 1,
      };
      GetUserList(params)
        .then((response) => {
          if (response.ErrorCode == 0) {
            var res = response.Result.rows;
            res.map((item) => {
              item.value = item.UserID;
              item.text = item.UserName;
            });
            this.sampleUserIdArr = res;
          }
        })
        .catch(() => {});
    },
    getClassTree() {
      var params = {
        pageModel: { search: [""], Token: this.token },
      };
      getInfoTree(params)
        .then((response) => {
          if (response.ErrorCode == 0) {
            var res = response.Result.rows;
            res.map((item) => {
              item.value = item.id;
              item.text = item.name;
            });
            this.classArr = res;
          }
        })
        .catch(() => {});
    },
    getSpecificationList() {
      var params = { Token: this.token, Code: this.rowData.stabilityPlanCode };
      GetSampleSpecificationSelect(params)
        .then((response) => {
          if (response.ErrorCode == 0) {
            var res = response.Result;
            this.SpecificationArr = res;
          }
        })
        .catch(() => {});
    },
    getUnitName(val) {
      this.Unit = val.value;
      this.UnitName = val.text;
    },
    getClassName(val) {
      this.ClassID = val.value;
      this.ClassName = val.text;
    },
    getSpecificationName(val) {
      this.Specification = val.value;
      this.SpecificationName = val.text;
    },
    delData(index) {
      this.checkList.splice(index, 1);
    },
    addCheckData() {
      if (this.ClassID == "") {
        Notify({ type: "danger", message: "班组不能为空！" });
        return false;
      }
      if (this.Count == "" || this.Unit == "") {
        Notify({ type: "danger", message: "检验数量单位不能为空！" });
        return false;
      }
      if (this.checkList.length > 0) {
      }
      var checkObj = {
        ClassID: this.ClassID,
        ClassName: this.ClassName,
        Count: this.Count,
        Unit: this.Unit,
        UnitName: this.UnitName,
        Specification: this.Specification,
        SpecificationName: this.SpecificationName,
        ResidueCount: this.ResidueCount,
      };
      var isSameClass = false;
      if (this.checkList.length > 0) {
        this.checkList.map((item) => {
          if (
            item.ClassID == checkObj.ClassID &&
            item.Specification == checkObj.Specification &&
            item.Count == checkObj.Count &&
            item.Unit == checkObj.Unit
          ) {
            isSameClass = true;
          }
        });
      }
      if (isSameClass) {
        Notify({ type: "warning", message: "数据已存在" });
        return false;
      }
      this.checkList.push(checkObj);
    },
    updataSampleUserId(val) {
      this.sampleUserId = val;
    },
    formatter(value, fmt) {
      if (!value) {
        return "";
      }
      let date = new Date(value);
      if (date === "Invalid Date") {
        date = new Date(parseFloat(value));
      }
      if (!fmt) {
        fmt = "yyyy-MM-dd";
      }
      const o = {
        "M+": date.getMonth() + 1, // 月份
        "d+": date.getDate(), // 日
        "h+": date.getHours(), // 小时
        "m+": date.getMinutes(), // 分
        "s+": date.getSeconds(), // 秒
        "q+": Math.floor((date.getMonth() + 3) / 3), // 季度
        S: date.getMilliseconds(), // 毫秒
      };
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          `${date.getFullYear()}`.substr(4 - RegExp.$1.length)
        );
      }
      Object.keys(o).forEach((k) => {
        if (new RegExp(`(${k})`).test(fmt)) {
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length === 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length)
          );
        }
      });
      return fmt;
    },
  },
  async created() {
    this.token = localStorage.getItem("tokenKey");
    this.rowData = JSON.parse(this.$route.params.paramData);
    this.testId = this.rowData.testID;
    this.getInfoByTestId();
    // this.getSampleUserId();
    this.getClassTree(); //班组
    this.getSpecificationList(); //规格
    this.attributeList = this.rowData.attributeList; //检验项目
    var str = "";
    this.attributeList.map((item, index) => {
      if (index == 0) {
        str += item.AttributeName;
      } else {
        str += "," + item.AttributeName;
      }
    });
    this.attributeStr = str;
  },
  mounted() {
    this.sampleDate = this.formatter(this.currentDate, "yyyy-MM-dd"); //取样时间
  },
};
</script>
<style lang="less" scoped>
.form-wapper {
  height: 100%;
  overflow: hidden;
}
.sampleItem {
  height: calc(100% - 1rem);
  overflow: auto;
}
.van-row {
  background: #fff;
}
.van-hairline-unset--top-bottom::after,
.van-hairline--top-bottom::after {
  border-width: 0;
}
.checkItem {
  width: 100%;
  padding: 0 10px;
  margin-top: 20px;
  box-sizing: border-box;
  font-size: 12px;
}
.checkItem > div {
  border: 1px solid #ccc;
}
.itemTit {
  height: 40px;
  background: #49bbef;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 10px;
  color: #fff;
}
.itemTit button {
  color: #000;
}
.itemContent {
  padding: 10px 10px 0 10px;
  width: 100%;
  box-sizing: border-box;
}
.readonly /deep/.van-field__body {
  background: #ddd;
}
/deep/.van-cell {
  padding: 0.2rem 0.4rem;
}
/deep/.van-field__body {
  border-radius: 2px !important;
  border: 1px solid #ddd;
}
/deep/.van-cell {
  font-size: 0.32rem;
}
.tb {
  border-collapse: collapse;
  width: 100%;
  font-size: 0.32rem;
}
.tb th {
  background-color: #49bbef;
  color: white;
}

.tb td,
.tb th {
  padding: 5px;
  border: 1px solid #ccc;
  text-align: center;
}
</style>